package dao

import (
	"fmt"
	"go-chi-restful-api/settings"
	"go-chi-restful-api/types"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var db *gorm.DB

// 初始化MySQL连接
func InitMySQL(cfg *settings.MySQLConfig) (err error) {
	// "user:password@tcp(host:port)/dbname"

	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=true&loc=Local", cfg.User, cfg.PassWord, cfg.Host, cfg.Port, cfg.DB)

	db, err = gorm.Open(mysql.Open(dsn))
	if err != nil {
		fmt.Printf("open mysql failed, err: %s \n", err)
		return
	}

	sqlDB, _ := db.DB()
	sqlDB.SetMaxOpenConns(cfg.MaxOpenConns)
	sqlDB.SetMaxIdleConns(cfg.MaxIdleConns)

	return sqlDB.Ping()
}

// 通过专栏id获取专栏会员页面信息
func GetColumnByID(id string) (column *types.Column, err error) {
	column = new(types.Column)

	if err = db.Debug().Where("id=?", id).First(column).Error; err != nil {
		return nil, err
	}
	return
}

// 通过专栏id获取专栏目录
func GetColumnDirectoryByID(columnID string) (chapters []types.Chapter, err error) {

	if err = db.Debug().Where("column_id=?", columnID).Find(&chapters).Error; err != nil {
		return nil, err
	}
	return
}

// 通过专栏id、章节id获取章节内容
func GetColumnChapterTextByID(chapterID string, columnID string) (chapter *types.Chapter, err error) {
	chapter = new(types.Chapter)

	if err := db.Where("id = ? and  column_id= ?", chapterID, columnID).First(&chapter).Error; err != nil {
		return nil, err
	}
	return
}
